package main

import (
	"log"
	"os"
	"text/template"
)

type User struct {
	Name   string `json:"user"`
	Native bool   `json:"native,omitempty"`
	Age    int
	HB     []string `json:"hobby"`
}

const tmpl = `{{range .}} {{/*这里遍历切片u1*/}}
{{$name := .Name}} {{$name |printf "%q"}} {{if .Native}}是本国人{{else}}不是本国人{{end}}
爱好：{{with .HB}}{{/*这里是判断.HB是否为空*/}}{{range .}} {{.}} {{end}} {{else}} 空({{$name}}居然没爱好!) {{end}}
-------------------------------
{{end}}`

func main() {
	u1 := []User{
		{Name: "Zhang San", Native: true, Age: 32, HB: []string{"surfing", "movie", "fishing"}},
		{Name: "Li Si", Native: true, Age: 23, HB: []string{"photoing", "swiming", "writing"}},
		{Name: "John Smith", Native: false, Age: 22, HB: []string{}},
	}

	temp, e := template.New("temp1").Parse(tmpl) //如果使用template.Must(*Template)，则不用判断err，因为Must()已经处理了
	if e != nil {
		log.Fatal(e)
	}
	if err := temp.Execute(os.Stdout, u1); err != nil { //可以使用temp.ExecuteTemplate(io.writer, tmpl_name string, data interface{}) 执行特定模板名
		log.Fatal(err)
	}
}
